<template>
  <el-card>
    <div slot="header">
      <h3>潜在验收标准-新增（竖版）</h3>
    </div>
    <div>
      <BtnRender :render="renderBtnsBar" />
      <el-divider />
      <el-checkbox v-model="isMustHave" @change="handleChangeMustHave">只展示必填项</el-checkbox>
      <SkusTable
        showActionCol
        :tableHeight="480"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :actionRender="renderTableBtnAction"
      />
    </div>
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="updateSkusBySeniorLinked"
    />
    <AccumulationAssociate
      :visible.sync="associateGoods.visible"
      :form-items="associateGoods.formItems"
      :columns="associateGoods.columns"
      :load-data="loadAssociateGoodsData"
      @update="updateSkusByAssociateGoods"
    />
  </el-card>
</template>
<script>
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import InputNumber from '@/components/inputNumber/inputNumber';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import AccumulationAssociate from '@/components/AssociateGoods/Accumulation';
import { TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import {
  createExcelByExport,
  generateUuid,
  isResponseSuccess,
} from '@/utils/bizUtils';
import { getHorizonChangeValue } from './utils';
import {
  TABLE_COLUMNS,
  ATTR_TYPE_ENUM,
  ASSOCIATE_FORM_ITEMS,
  ASSOCIATE_TABLE_COLUMNS,
} from './constants/horizontalEdit';
import { WHETHER_ENUMS } from '@/constants/commodity';
import {
  getSkuInfoWithPermissionService,
  getHorizontalInitDataWithPermissionService,
  exportHorizontalDataService,
  importHorizontalDataUrl,
  saveHorizontalDataService,
} from '@api/commodity/temporaryPurchasingGoods/acceptanceStandard';
export default {
  name: 'HorizontalEdit', // 批量维护验收标准（竖版）
  components: {
    BtnRender,
    SkusTable,
    InputNumber,
    SeniorLinkedDialog,
    AccumulationAssociate,
  },
  data () {
    return {
      isMustHave: false, // 只展示必填项
      skuNos: [],
      sourceList: [], // 原始数据
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea' }],
        dataSource: [{ skuNo: '' }],
      },
      associateGoods: {
        visible: false,
        formItems: ASSOCIATE_FORM_ITEMS,
        columns: ASSOCIATE_TABLE_COLUMNS,
      },
      btnLoading: {
        export: false, // 导出按钮loading
        submit: false, // 提交按钮loading
      }
    }
  },
  created () {
    this.updateColumns()
  },
  methods: {
    // 渲染表头按钮操作栏
    renderBtnsBar (h) {
      const btnList = [
        {
          label: '高级关联',
          method: this.handleSeniorLinked,
          hasAuth: true,
        },
        {
          label: '关联商品',
          method: this.handleAssociateGoods,
          hasAuth: true,
        },
        {
          label: '导出',
          method: this.handleExport,
          disabled: this.TableInfo.isNullList(),
          loading: this.btnLoading.export
        },
        {
          label: '导入',
          action: importHorizontalDataUrl,
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: this.TableInfo.setLoading
        },
        {
          label: '提交',
          method: this.handleSubmit,
          disabled: this.TableInfo.isNullList(),
          loading: this.btnLoading.submit
        }
      ]
      return getListPageBtnsBar(h, btnList)
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [{ label: '删除', method: this.handleDelete }]
      return getTableAction({ h, row, actionList })
    },
    // 删除
    handleDelete (row) {
      const updateList = this.TableInfo.list.filter(item => item.skuNo != row.skuNo)
      this.TableInfo.setList(updateList)
      this.updateSourceList(updateList)
    },
    // 高级关联
    handleSeniorLinked () {
      this.seniorLinked.visible = true
    },
    // 关联商品
    handleAssociateGoods () {
      this.associateGoods.visible = true
    },
    // 导出
    async handleExport () {
      const data = { commitList: this.TableInfo.list }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportHorizontalDataService(data, loadingFn)
      const uuid = generateUuid()
      createExcelByExport({ excelTitle: `潜在商品验收标准（竖版）_${uuid}`, res })
    },
    // 导入成功
    handleUploadSuccess (res) {
      if (isResponseSuccess(res)) {
        this.isMustHave = false
        this.TableInfo.setList(res?.retData)
        this.updateSourceList(res?.retData)
      }
    },
    // 提交
    async handleSubmit () {
      const data = { commitList: this.TableInfo.list }
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await saveHorizontalDataService(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('提交成功')
        setTimeout(() => {
          window.close()
        }, 1000)
      }
    },
    // 只展示必填项
    handleChangeMustHave (val) {
      this.updateSourceList()
      const updateList = val
        ? this.sourceList.filter(item => item.mustHave == WHETHER_ENUMS.Yes)
        : this.sourceList
      this.TableInfo.setList(updateList)
    },
    // 加载关联商品集合
    loadAssociateGoodsData (configs) {
      const { formData, paginationParams, loadingFn } = configs ?? {}
      const data = {
        ...formData,
        ...paginationParams
      }
      return getSkuInfoWithPermissionService(data, loadingFn)
    },
    // 更新高级关联商品集合
    updateSkusBySeniorLinked (skuNos) {
      this.skuNos = _.uniq([...this.skuNos, ...skuNos])
      this.updateTableList()
    },
    // 更新关联商品集合
    updateSkusByAssociateGoods (skuVos) {
      const skuNos = skuVos.map(item => item.skuNo)
      this.skuNos = _.uniq([...this.skuNos, ...skuNos])
      this.updateTableList(skuNos)
    },
    // 更新表格数据
    async updateTableList () {
      const data = { skuNos: this.skuNos }
      const res = await getHorizontalInitDataWithPermissionService(data, this.TableInfo.setLoading)
      if (!isResponseSuccess(res)) {
        this.skuNos = []
      }
      this.isMustHave = false
      this.TableInfo.setList(res?.retData)
      this.updateSourceList(res?.retData)
    },
    // 更新源数据集合
    updateSourceList (list) {
      this.sourceList = list ?? this.sourceList
      this.sourceList.forEach(item => {
        const target = this.TableInfo.list.find(row => row.uuid == item.uuid)
        if (!target) return
        item.attrValueName = target.attrValueName
        item.attrValueCode = target.attrValueCode
      })
    },
    // 更新表列
    updateColumns () {
      const updateColumns = [
        ...TABLE_COLUMNS,
        {
          title: '属性值',
          width: 120,
          render: this.getAttrTypeRender
        }
      ]
      this.TableInfo.setColumns(updateColumns)
    },
    // 获取属性类型渲染
    getAttrTypeRender (h, { row }) {
      // 文本框
      const getTextRender = () => (
        <el-input
          vModel_trim={row.attrValueName}
          size="mini"
          disabled={!row.canEdit}
          onChange={val => { this.textValChange(row, val) }}
        />
      )
      // 数字框
      const getNumberRender = () => (
        <InputNumber
          v-model={row.attrValueName}
          style="width: 100%;"
          size="mini"
          controls={false}
          disabled={!row.canEdit}
        />
      )
      // 下拉框
      const getSelectRender = () => (
        <el-select
          v-model={row.attrValueCode}
          placeholder="请选择"
          clearable
          size="mini"
          onChange={val => row.attrValueName = row.selOptList.find(
            item => item.optionValue == val
          )?.optionHtml ?? ''}
          disabled={!row.canEdit}
        >
          {(row.selOptList ?? []).map(item => (
            <el-option
              key={item.optionValue}
              label={item.optionHtml}
              value={item.optionValue}
            />
          ))}
        </el-select>
      )
      if (row.attrType == ATTR_TYPE_ENUM.Text) return getTextRender()
      if (row.attrType == ATTR_TYPE_ENUM.Number) return getNumberRender()
      if (row.attrType == ATTR_TYPE_ENUM.Select) return getSelectRender()
    },
    // 文本框值变化
    textValChange (row) {
      this.standardValChange(row)
    },
    // 标准值变更逻辑
    standardValChange (row) {
      const {
        upDiffValueIndex,
        downDiffValueIndex,
        upDiffValue,
        downDiffValue
      } = getHorizonChangeValue(row, this.TableInfo.list) ?? {}
      if (upDiffValueIndex > -1) {
        this.TableInfo.list[upDiffValueIndex].attrValueName = upDiffValue
      }
      if (downDiffValueIndex > -1) {
        this.TableInfo.list[downDiffValueIndex].attrValueName = downDiffValue
      }
    },
  }
}
</script>
<style lang="less" scoped>
.el-divider--horizontal {
  margin: 12px 0;
}
</style>
